function getURLQueryParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        if (name == 'redirect') {
         return decodeURIComponent(r[2]) + window.location.hash
        } else {
         return decodeURIComponent(r[2])
        }
    }
    return '';
}
function getI18n(key) {
    return $t(key);
}
function forwardPrivacy() {
    //闅愮鏀跨瓥
    var logintargetUrl = encodeURIComponent((getURLQueryParam("redirect") || targetUrl));
    var herf = uniportalContextPath + '/privacyPolicyInter.html?redirect=' + logintargetUrl;
    window.open(herf, '_blank');
}
function getInterface() {
    axios
        .get(contact, {})
        .then(function(res) {
            if(res.data && document.getElementsByClassName("public-footer-center").length > 0){
                document.getElementsByClassName("public-footer-center")[0].innerHTML =res.data.copyright
                if(document.getElementsByClassName("footerHwEmail")[0]){
                    document.getElementsByClassName("footerHwEmail")[0].innerHTML =res.data.copyright
                }
            }
                //鑱旂郴鎴戜滑url
            if (document.querySelector("#isPrivacyMobile")) {
                document.querySelector("#isPrivacyMobile").href = res.data.contactUs
            }

            if (document.querySelector("#isPrivacyPC")) {
                document.querySelector("#isPrivacyPC").href = res.data.contactUs
            }
                window.contactUs = res.data.contactUs
        })
        .catch(function(error) {
            console.log(error)
        })
}
(function() {
    var _urlRoot = (function() {
        var pathname = location.pathname.toLowerCase();
        var is1 = false;
        var is2 = false;
        var url1 = {
            accounts: "/accounts1",
            myAccount: "/myaccount1",
            uniportal: "/uniportal1"
        };
        var url2 = {
            accounts: "/accounts2",
            myAccount: "/myaccount2",
            uniportal: "/uniportal2"
        };
        var url3 = {
            accounts: "/accounts1",
            myAccount: "/usercenter",
            uniportal: "/login1"
        };
        for (var key in url1) {
            if (pathname.indexOf(url1[key]) === 0) {
                is1 = true;
                break;
            }
        }
        if (is1 === true) {
            return url1;
        }
        for (var key in url2) {
            if (pathname.indexOf(url2[key]) === 0) {
                is2 = true;
                break;
            }
        }
        return is2 ? url2 : url3;
    })();
    var _targetUrl = (function() {
        var currentHostName = window.document.location.hostname;
        var myaccountPath = _urlRoot.myAccount;

        return "https://" + currentHostName + myaccountPath;
    })();
    var Base_API = {
        //鐧诲綍椤甸潰鍦板潃
        languageHttpserver: '/rest/hwidcenter/languages',
        validHttpserver: '/rest/hwidcenter/validate-account',
        loginHttpserver: '/rest/hwidcenter/login',
        smloginHttpserver: '/rest/hwidcenter/sm-login',
        msgcodeHttpserver: '/rest/hwidcenter/sm-code',
        getThirdUrl: '/rest/hwidcenter/app-policy',
        toThirdloginUrl: '/oauth2',
        changeLange: '/rest/hwidcenter/change-lang',
        contact: '/rest/hwidcenter/get-copyright-contact-us', // 鑱旂郴鎴戜滑/鐗堟潈淇℃伅
        privacy: '/rest/hwidcenter/get-privacy-statement', //闅愮鍗忚
        AccountOper: '/rest/hwidcenter/accountOperationLink', //闅愮鍗忚
        // //鍙屽洜瀛愰獙璇佸湴鍧€
        // loginRisk:'/rest/hwidcenter/login',
        accoutnInfo:'/rest/hwidcenter/mfa/account-info',
        sendVerfyCode:'/rest/hwidcenter/mfa/send-verfy-code',
        validataVerfyCode:'/rest/hwidcenter/mfa/validate-verify-code',
        initusername:'/rest/hwidcenter/get-remember-account'
        // smCode:'/rest/hwidcenter/mfa/sm-code',

    }

    var baseURL = { url: getUniportalContextPath() };
    for (var key in Base_API) {
        Base_API[key] = baseURL.url + Base_API[key];
        window[key] = Base_API[key];
    }

    function getTargetUrl() {
        return _targetUrl;
    }

    function getLoginFlag(uniportalContextPath) {
        if (uniportalContextPath == '/login1' || uniportalContextPath == '/login2' || uniportalContextPath == '/login3') {
            return true;
        }
        return false;
    }

    function getMyAccountContextPath() {
        return _urlRoot.myAccount;
    }

    function getAccountsContextPath() {
        return _urlRoot.accounts;
    }

    function getUniportalContextPath() {
        return _urlRoot.uniportal;
    }
    window.getMyAccountContextPath = getMyAccountContextPath
    window.getAccountsContextPath = getAccountsContextPath
    window.getUniportalContextPath = getUniportalContextPath
    window.getTargetUrl = getTargetUrl
    window.getLoginFlag = getLoginFlag
    window.contactUs = ''
})();

//*******************************************************************************************鍩嬬爜Start
// ********************浠ヤ笂鑾峰彇鐜鍙橀噺鐨勪唬鐮佷粎渚涘弬鑰冿紝璇蜂互鎮ㄧ殑瀹為檯鐜鍒ゆ柇涓哄噯锛�******************
// 椤甸潰缁勪欢鍩嬬爜
function uemTrackStructEvent(uemId) {
    try {
        window.hwa && window.hwa('trackStructEvent', {
            uem_id: uemId, // 鍦║EM娉ㄥ唽鐨勬帶浠惰祫浜D(蹇呭～)
            duration: 236, // 鎺т欢鎿嶄綔鑰楁椂(鍙€�,鍗曚綅鏄绉抦s)
            data: {user_role: '', sub_page: ''} // 涓氬姟鎵╁睍瀛楁鏁版嵁锛寀ser_role:鐢ㄦ埛瑙掕壊锛宻ub_page:閫昏緫椤甸潰鏍囪瘑锛岃纭繚鎵╁睍鏁版嵁閲屼笉鑳藉惈鏈変笉绗﹀悎闅愮鍚堣瑕佹眰鐨勬晱鎰熸暟鎹紒涓斿瓧娈靛唴瀹瑰湪1024瀛楄妭闀垮害浠ュ唴锛�
        })
    } catch (e) {
    }
}

function initUemConfig(op) {
    let url = 'rest/hwidcenter/get-uemconfig'
    if (top !== self) {
        url += '/?domain=' + document.referrer
    }
    axios.get(url).then(function (res) {
        let isCspSwitch = res.data.isCspSwitch
        if (top !== self && isCspSwitch) {
            window.location.href = "/login1/errorPage.html?errorCode=E_10012";
            return;
        }

        var hwaAppKeys = JSON.parse(res.data.hwaAppKeysJson)
        hwaAppKeys.isEnableUem = res.data.isUEMSwitch
        initHwaConfig(window, document, hwaAppKeys, 'hwa')
        if (typeof op !== 'undefined' && typeof op.init === 'function') {
            op.init()
        }
    }).catch(function (error) {
    })
}

function getinitusername(){
    axios
    .get(initusername, {
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
         rememberAccountName:true,
         localStorage:localStorage.getItem('loginAccount') || localStorage.getItem('checked')
       }
    })
    .then(function (res) {
            //淇濆瓨鐧诲綍鐢ㄦ埛鍚�      
            try {
                if (localStorage.getItem('rememberAccountName') === 'true') {
                    document.getElementById("username").value = localStorage.getItem('loginAccount')!=='null' ?  localStorage.getItem('loginAccount') : '';
                    document.getElementById("checked").checked = true;
                } else {
                    document.getElementById("username").value = '';
                }
            } catch (err) { }
    })
}

// 椤甸潰鍩嬬爜
function uemTrackPageView(pageCode, subPageName) {
    try {
        window.hwa && window.hwa('trackPageView', pageCode, {sub_page: subPageName, user_role: ''})
    } catch (e) {
    }
}
function initHwaConfig(h, w, f, t) {
// 閲囬泦鍣ㄩ厤缃�
    try {
        if (!h[t]) {
            h.GlobalHwaNamespace = h.GlobalHwaNamespace || []
            h.GlobalHwaNamespace.push(t)
            h[t] = function () {
                (h[t].q = h[t].q || []).push(arguments)
            }
            if (!f.isEnableUem) {
                return
            }
            h.trackerload = function () {
                (h[t].q = h[t].q && h[t].q.length ? h[t].q : []).unshift(arguments)
            }
            h[t].q = h[t].q || []
        }

        var host = (f.env === 'pro') ? 'hwa.his.huawei.com' : ((f.env === 'beta') ? 'hwa-beta.his.huawei.com' : '')
        var welinkHost = ''
        if (f.platform === 'welink') {
            host = ((f.env === 'pro') ? 'w3m.huawei.com/mcloud/umag' : ((f.env === 'beta') ? 'mcloud-uat.huawei.com/mcloud/umag' : ''))
            welinkHost = host + '/ProxyForText/hwa_trackload'
            h.hwahost = welinkHost
            host = host + '/fg/ProxyForDownLoad/hwa_f'
        }
        h.aids = f
        h.space = t
        var ts = new Date().getFullYear() + '' + new Date().getMonth() + '' + new Date().getDate()
        var script = w.createElement('script')
        script.id = 'uem_f'
        script.src = (location.protocol === 'https:' ? 'https://' : 'http://') + host + '/dist/uem_f.js?v=' + (ts)
        if (!(f.async === false)) {
            script.setAttribute('async', '1')
        }
        script.setAttribute('style', 'display:none')
        var where = w.getElementsByTagName('head')[0].firstChild || w.getElementsByTagName('head')[0].lastChild || w.getElementsByTagName('script')[0]
        if (where) {
            where.parentNode.insertBefore(script, where)
        } else {
            w.getElementsByTagName('head')[0].appendChild(script)
        }
    } catch (e) {
        if (!h[t]) h[t] = function () { }
    }
}
//If the field is empyt or larger than expected length,
//then return error message otherwise return ""
function checkLength(field,maxLength,nls,label,ref, vm){
	var emptyMessage = "Please enter the " + label + ".";
	var overLength = label + " length not more than " +
		 maxLength + ",Please re-input!";
	if(nls == "zh" || nls == "zh_CN") {
		emptyMessage = "\u8bf7\u8f93\u5165" + label;
		overLength = label + "\u7684\u957f\u5ea6\u4e0d\u80fd\u5927\u4e8e" + 
			maxLength + "\u4e2a\u5b57\u8282\uff0c\u8bf7\u91cd\u65b0\u586b\u5199!";
	}
	var value = field.value;
	if(isEmpty(value)) {
        getfocus(ref, vm)
		return emptyMessage;
	}
	if (getTextLen(value) > maxLength) {
        getfocus(ref, vm)
		return overLength;
	}
	return "";
}
function getfocus(ref, vm){
    vm.$refs[ref].focus()
}
//return the length of the text s
function getTextLen(s) {
    var newlength=0;
    for(i=0;i < s.length;i++) {
		var chrInput;
		chrInput = escape(s.charAt(i));
		if(chrInput.length==6) newlength = newlength+3;
		else newlength = newlength+1;
    }
    return newlength;
}
//the the text s is null or empty
function isEmpty(value){ 
	return ((value == null) || (trim(value).length == 0));
}
function trim(s) {
	var tempStr;
	tempStr = s.replace(/\s+$/g,'');
	tempStr = tempStr.replace(/^\s+/g,'');
	return tempStr;
}

function urlSpecialSymbolProcessing(url) {
    try {
        return url.replaceAll('#', '%23')
    } catch (e) {
        console.log(e)
    }
    return url;
}

function getUrlAppId(name) {
    if (getURLQueryParam('idaas_ext_field')) {
        const idaasExtField = atob(getURLQueryParam('idaas_ext_field'));
        const idaasExtFieldObj = JSON.parse(idaasExtField);
        return idaasExtFieldObj[name] ? idaasExtFieldObj[name] : '';
    }

    let searchUrl = decodeURIComponent(decodeURI(window.location.search));
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    let urlNew = searchUrl.substr(1).match(reg);
    if (urlNew != null) {
        return unescape(urlNew[2].split('#')[0]);
    } else {
        return '';
    }
}

// 瑙ｇ爜涓嶇煡閬撶紪鐮佸灏戞鐨勫湴鍧€
function checkDecodeUrl(targetUrl) {
    if (decodeURIComponent(targetUrl) === targetUrl) {
        return targetUrl;
    } else {
        return arguments.callee(decodeURIComponent(targetUrl));
    }
}

/**
 * cookie鏂规硶
 * @param {*}
 */
function setCookie(key, value, time) {
    var times = new Date();
    times.setDate(times.getDate() + time);
    document.cookie = key + '=' + value + ';expires=' + times;
}
function getCookieVal(key) {
    var cookie = document.cookie;
    var cookieArr = cookie.split(';');
    for(let k = 0; k < cookieArr.length; k++) {
        var res = cookieArr[k].split('=');
        if(res[0].trim() == key) {
        return res[1];
        }
    }
}
function removeCookie(key) {
    setCookie(key,'', -1)
}